
import java.util.logging.Level;
import java.util.logging.Logger;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author Nathan
 */
public class Rider implements Runnable {
    
    private Building b;
    private int id;
    private int currentFloor;
    private int destFloor;
    
    
    public Rider(Building build, int ident, int currFloor, int destination) {
        b = build;
        id = ident;
        currentFloor = currFloor;
        destFloor = destination;
    }
    
    public void run() {
        if (currentFloor < destFloor) {
        	Elevator e = null;
			b.write(Thread.currentThread().getName() + ": R" + id +
                    " pushes U" + currentFloor);
        	while (e == null) {
        		e = b.CallUp(currentFloor);
        	}
        	
        	synchronized(e) {
	        	b.write(Thread.currentThread().getName() + ": R" + id +
	                    " enters E" + e.getID() + " on F" + currentFloor);
	            e.Enter();
	            
	            b.write(Thread.currentThread().getName() + ": R" + id +
	                    " pushes E" + e.getID() + "B" + destFloor);
	            e.RequestFloor(destFloor);
        	
            
	            while(e.getCurrentFloor() != destFloor) {
		            try {
		            	e.wait();
		            } catch (InterruptedException ex) {
		                Logger.getLogger(Rider.class.getName()).log(Level.SEVERE, null, ex);
		            }
	            }
	            b.write(Thread.currentThread().getName() + ": R" + id +
	                    " exits E" + e.getID() + " on F" + destFloor);
        	}
            
            e.Exit();
        }
        else if (currentFloor > destFloor) {
        	Elevator e = null;
			b.write(Thread.currentThread().getName() + ": R" + id +
                    " pushes D" + currentFloor);
        	while (e == null) {
        		e = b.CallDown(currentFloor);
        	}
        	

        	synchronized(e) {
	        	b.write(Thread.currentThread().getName() + ": R" + id +
	                    " enters E" + e.getID() + " on F" + currentFloor);
	            e.Enter();
	            
	            b.write(Thread.currentThread().getName() + ": R" + id +
	                    " pushes E" + e.getID() + "B" + destFloor);
	            e.RequestFloor(destFloor);
        	

	            while(e.getCurrentFloor() != destFloor) {
		            try {
		            	e.wait();
		            } catch (InterruptedException ex) {
		                Logger.getLogger(Rider.class.getName()).log(Level.SEVERE, null, ex);
		            }
	            }
	            b.write(Thread.currentThread().getName() + ": R" + id +
	                    " exits E" + e.getID() + " on F" + destFloor);
        	}    
            
            e.Exit();
        }
    }
}